package org.project.choujiang.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import org.project.choujiang.utils.TokenUtils;
import org.project.choujiang.pojo.ro.R;
import org.project.choujiang.pojo.domain.User;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginFilter implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        String requestURI = request.getRequestURI();
        if ("/login/login".equals(requestURI) || "/login/getUserInfo".equals(requestURI)  || requestURI.matches("^/file/.*")){
            return true;
        }else {
            try {
                User loginUserInfo = TokenUtils.getLoginUserInfo();
                if (ObjectUtil.isNull(loginUserInfo))
                    throw new IllegalArgumentException("请先登录");
                else
                    return true;
            } catch (Exception e) {
                response.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.JSON.getValue()+";charset=utf-8");
                response.getWriter().write(JSONUtil.toJsonStr(R.redl(e.getMessage())));
            }
        }
        return false;
    }
}
